<!--  -->
<template>
  <div class="goods-detail" v-if="detailData">
    <!-- 详情页的头部 -->
    <div class="goods-header" ref="goodsHeader">
      <i :class="['iconfont', 'icon-jiantou3', iconBg]" @click="goBackBtn"></i>
      <!-- tabs -->
      <div class="detail-tabs" ref="detailTabs">
        <ul>
          <li v-for="(detailTab, index) in detailTabs" :key="detailTab.id" :class="activeIndex == index ? 'active' : ''"
            @click="toggleTabs(index)">
            {{ detailTab.title }}
          </li>
        </ul>
      </div>
      <!-- 收藏 -->
      <i :class="['iconfont', 'icon-gerenguanzhu', iconBg]"></i>
      <!-- 更多 -->
      <i :class="['iconfont', 'icon-gengduo', iconBg]"></i>
    </div>
    <!-- 商品展示内容 -->
    <div class="goods-info detail_0 floors">
      <div class="goods_photo_wrap">
        <mt-swipe :show-indicators="false" :auto="0" @change="handleChange">
          <mt-swipe-item v-for="item in detailData.gallery_list" :key="item.img_id">
            <img :src="item.img_url" alt="" />
          </mt-swipe-item>
        </mt-swipe>
        <div class="custom-indicator">
          <span class="current">{{ swiperIndex }}</span>/
          <span>{{ detailData.gallery_list.length }}</span>
        </div>
      </div>
      <!-- 商品的价格 -->
      <div class="goods-price">
        <div class="currency-price">
          <em>¥</em>
          <!-- 整数 -->
          <span>{{ detailData.shop_price | setInt }}</span>
          <!-- 小数 -->
          <em>{{ detailData.shop_price | setFloat }}</em>
        </div>
        <!-- 原价价格 -->
        <div class="rebate-price">
          <del>{{ detailData.market_price_formated }}</del>
        </div>
        <div class="sold_out">已售{{ detailData.sales_volume }}件</div>
        <!-- 海报生成弹出 -->
        <div class="share" @click="showPosterFun">
          <i class="iconfont icon-fenxiang"></i>
          <span>分享</span>
        </div>
      </div>
      <div class="goods_title">
        <em class="tag">{{ detailData.ru_id === 0 ? "自营" : "进店" }}</em>
        <span>{{ detailData.goods_name }}</span>
      </div>
      <!-- 已选及地址选择的内容 -->
      <div class="goods_module_wrap">
        <div class="activity_content">
          <div class="title">已选</div>
          <div class="activity_main">{{ buyNum }}</div>
          <i class="iconfont icon-gengduo1" @click="selectPopshow"></i>
        </div>
        <!-- 地址 -->
        <div class="activity_content">
          <div class="title">送至</div>
          <div class="activity_main">{{ fieldValue }}</div>
          <i class="iconfont icon-gengduo1" @click="addressPopshow"></i>
        </div>
        <div class="activity_content">
          <div class="title">运费</div>
          <div class="activity_main">包邮</div>
          <i class="iconfont icon-gengduo1"></i>
        </div>
        <div class="activity_content">
          <div class="title">服务</div>
          <div class="activity_main">支持7天无理由退货</div>
          <i class="iconfont icon-gengduo1"></i>
        </div>
      </div>
    </div>
    <!-- 已选框的弹出框 -->
    <div class="select-buy">
      <!-- 商品详情的内容 -->
      <van-popup v-model="show" closeable position="bottom">
        <div class="goods-wrap">
          <div class="goods-img">
            <img :src="detailData.goods_thumb" alt="" />
          </div>
          <div class="goods-content">
            <div class="title">
              {{ detailData.goods_name }}
            </div>
            <!-- 流通价格 -->
            <div class="currency-price">
              <span>
                <em>¥</em>
                <!-- 整数部分 -->
                <span>{{ detailData.shop_price | setInt }}</span>
                <!-- 小数部分 -->
                <em>{{ detailData.shop_price | setFloat }}</em>
              </span>
            </div>
          </div>
        </div>
        <!-- 数量的内容 -->
        <div class="num-wrap">
          <h3>数量</h3>
          <div>
            <van-stepper v-model="buyNum" integer />
          </div>
        </div>
        <!-- 加入购物车和立即购买按钮 -->
        <div class="oper-wrap">
          <button class="addCart" @click="addCart">加入购物车</button>
          <button class="buy">立即购买</button>
        </div>
      </van-popup>
    </div>
    <!-- 地址的弹出框 -->
    <van-popup v-model="showAddress" round position="bottom">
      <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="options" @close="showAddress = false"
        @finish="onFinish" />
    </van-popup>
    <!-- 海报的弹出框 -->
    <van-popup v-model="showPoster">
      <!-- 绑定属性 -->
      <CreatePoster :detailData="detailData" />
    </van-popup>
    <!-- 评论 -->
    <div class="detail_1 floors">评论</div>
    <!-- 详情 -->
    <div class="detail_2 floors">
      详情
      <div v-html="detailData.goods_desc"></div>
    </div>
    <!-- 推荐 -->
    <div class="detail_3 floors">推荐</div>
    <!-- 脚部分 -->
    <div class="footer">
      <div class="shop" v-if="(detailData.ru_id != 0)">
        <i class="iconfont icon-dianpu"></i>
        <span>店铺</span>
      </div>
      <div class="kefu">
        <i class="iconfont icon-kefu2"></i>
        <span>客服</span>
      </div>
      <div class="cart" @click="toCart">
        <i class="iconfont icon-gouwuche"></i>
        <span>购物车</span>
        <em>{{ totalCount }}</em>
      </div>
      <button class="addCart" @click="addCart">加入购物车</button>
      <button class="buy">立即购买</button>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { DetailGoodsApi } from "@/api/detail";
import CreatePoster from "./components/CreatePoster.vue";
import cityData from "@/mock/city.json";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { CreatePoster },
  data() {
    //这里存放数据
    return {
      detailTabs: [
        { id: 1, title: "商品" },
        { id: 2, title: "评论" },
        { id: 3, title: "详情" },
        { id: 4, title: "推荐" },
      ],
      // tabs的index
      activeIndex: 0,
      detailData: null,
      // detailData: {
      //   goods_id: 672,
      //   goods_name:
      //     "华帝【年度旗舰】Huawei/华为 Mate 9 6+128GB 4G智能手机限量抢 麒麟960芯片 徕卡双镜头",
      //   marketPrice: "2799.60",
      //   market_price_formated: "¥2799.60",
      //   shop_price: "2333.00",
      //   shop_price_formated: "¥2333.00",
      //   // 销售量
      //   sales_volume: 4,
      //   goods_thumb: require("@/assets/images/goodsimg.jpg"),
      //   gallery_list: [
      //     {
      //       img_id: 882,
      //       img_url:
      //         "https://x.dscmall.cn/storage/images/201703/goods_img/0_P_1489108266997.jpg",
      //     },
      //     {
      //       img_id: 883,
      //       img_url:
      //         "https://x.dscmall.cn/storage/images/201703/goods_img/_P_1489108271727.jpg",
      //     },
      //     {
      //       img_id: 884,
      //       img_url:
      //         "https://x.dscmall.cn/storage/images/201703/goods_img/_P_1489108271043.jpg",
      //     },
      //     {
      //       img_id: 885,
      //       img_url:
      //         "https://x.dscmall.cn/storage/images/201703/goods_img/_P_1489108272459.jpg",
      //     },
      //   ],
      //   self_run: "",
      // },
      swiperIndex: 1,
      iconBg: "icon-bg",
      show: false,
      showAddress: false,
      cascaderValue: "",
      fieldValue: "河南省 郑州市 高新区",
      options: [
        {
          text: "浙江省",
          value: "330000",
          children: [{ text: "杭州市", value: "330100" }],
        },
        {
          text: "江苏省",
          value: "320000",
          children: [{ text: "南京市", value: "320100" }],
        },
      ],
      addressData: cityData.provinces.province,
      showPoster: false,
      buyNum: 1,
    };
  },
  //计算属性 类似于data概念
  computed: {
    totalCount() {
      let count = 0;

      let cartListDatas = this.$store.state.cartListDatas;
      cartListDatas.forEach(item => {
        item.goods.forEach(value => {
          count += value.goods_number;
        })
      })
      return count;
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 返回上一页
    goBackBtn() {
      //   this.$router.go(-1);
      this.$router.back();
    },
    // 切换tabs
    toggleTabs(index) {
      // 去掉滚动的影响
      // this.activeIndex = index;
      // 获取对应的楼层
      let targetEle = document.querySelector(".detail_" + index);
      // console.log(targetEle);
      // 算出来被卷进去的距离
      let scrollDis =
        targetEle.offsetTop -
        this.$refs.goodsHeader.offsetHeight -
        window.pageYOffset;
      // 缓慢滚动
      window.scrollBy({
        top: scrollDis,
        // 缓慢滑动
        behavior: "smooth",
      });
    },
    handleChange(index) {
      // console.log(index);
      this.swiperIndex = index + 1;
    },
    detailScrollFun() {
      if (document.documentElement.scrollTop >= 50) {
        this.$refs.detailTabs.className = "detail-tabs detail-tabs-scroll";
        this.$refs.goodsHeader.className = "goods-header goods-header-scroll";
        this.iconBg = "";
      } else {
        this.$refs.detailTabs.className = "detail-tabs";
        this.$refs.goodsHeader.className = "goods-header";
        this.iconBg = "icon-bg";
      }
      // 滑动时,让楼层进行改变
      var floors = document.querySelectorAll(".floors");
      var headerHeight = this.$refs.goodsHeader.offsetHeight;
      for (let i = 0; i < floors.length; i++) {
        // window.scrollY:得到滚动的距离
        // console.log("scrollY" + window.scrollY);
        // console.log("pageYOffset" + window.pageYOffset);
        if (window.pageYOffset + headerHeight >= floors[i].offsetTop) {
          this.activeIndex = i;
        }
      }
    },
    // 弹出已选的弹出框
    selectPopshow() {
      this.show = true;
    },
    addressPopshow() {
      this.showAddress = true;
    },
    onFinish({ selectedOptions }) {
      // 关闭弹出框
      this.showAddress = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join(" ");
    },
    // 获取省市区的函数
    getoptions() {
      let tempArr = [];
      // 所有省的数据获取
      for (let i = 0; i < this.addressData.length; i++) {
        let proObj = {};
        proObj = {
          text: this.addressData[i].ssqname,
          value: this.addressData[i].ssqid,
        };
        tempArr.push(proObj);
        // 初始化市的数据
        tempArr[i].children = [];
        for (var j = 0; j < this.addressData[i].cities.city.length; j++) {
          let cityObj = {
            text: this.addressData[i].cities.city[j].ssqname,
            value: this.addressData[i].cities.city[j].ssqid,
          };
          tempArr[i].children.push(cityObj);
          // 初始化区/县
          tempArr[i].children[j].children = [];
          for (
            let k = 0;
            k < this.addressData[i].cities.city[j].areas.area.length;
            k++
          ) {
            let areaObj = {
              text: this.addressData[i].cities.city[j].areas.area[k].ssqname,
              value: this.addressData[i].cities.city[j].areas.area[k].ssqid,
            };
            tempArr[i].children[j].children.push(areaObj);
          }
        }
      }
      this.options = tempArr;
    },
    // 弹出海报组件
    showPosterFun() {
      this.showPoster = true;
    },
    // 去购物页面
    toCart() {
      this.$router.push('/cartview');
    },
    // 添加购物车操作
    addCart() {
      // 准备商品数据添加到vuex中
      let cartData = {
        store_id: this.detailData.ru_id,
        store_name: this.detailData.rz_shopName,
        // 店铺是否选中
        checked: true,
        goods: [
          {
            // 店铺id
            store_id: this.detailData.ru_id,
            // 店铺的名称
            store_name: this.detailData.rz_shopName,
            // 商品是否选中
            is_checked: true,
            goods_id: this.detailData.goods_id,
            goods_name: this.detailData.goods_name,
            goods_price: this.detailData.shop_price,
            goods_thumb: this.detailData.goods_thumb,
            // 商品购买量
            goods_number: this.buyNum
          }
        ]
      }
      this.$store.commit("changeCartListDatas", cartData);
      // 关闭已选的弹窗
      this.show = false;
    }
  },
  beforeCreate() { }, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() { },
  beforeMount() { }, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

    // 进入详情页时,直接滚动到顶部
    window.scrollTo(0, 0);
    // 放置到monted
    DetailGoodsApi(this.$route.params).then((res) => {
      console.log(res.data.data);
      this.detailData = res.data.data;
      // 获取数据后,再绑定滚动事件
      // 绑定滚动事件
      document.addEventListener("scroll", this.detailScrollFun);
      // console.log(this.addressData);
      this.getoptions();
      console.log(this.detailData.self_run);
    });
  },
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() { }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() {
    // 全局事件的销毁removeEventListener
    document.removeEventListener("scroll", this.detailScrollFun);
  }, //生命周期 - 销毁完成
  activated() { }, //如果页面有keep-alive缓存功能，激活
  deactivated() { }, //如果页面有keep-alive缓存功能，非激活
};
</script>
<style lang="less">
.goods-detail {

  // 头部
  .goods-header {
    height: 5rem;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    display: flex;
    width: calc(100% - 2rem);
    align-items: center;
    // justify-content: space-between;
    justify-content: center;
    padding: 0 1rem;
    color: #fff;

    i {
      width: 2.5rem;
      height: 2.5rem;
      line-height: 2.5rem;
      text-align: center;
      border-radius: 50%;
      margin-right: 1rem;
    }

    .icon-bg {
      background: rgba(41, 47, 54, 0.4);
    }

    .detail-tabs {
      width: 65%;
      opacity: 0;
      transition: opacity 0.5s;

      ul {
        display: flex;

        li {
          flex: 1;
          text-align: center;
        }

        .active {
          color: #000;
          font-size: 1.6rem;
          font-weight: 700;
          position: relative;

          &::after {
            content: "";
            position: absolute;
            left: 28%;
            bottom: -0.9rem;
            width: 2.6rem;
            height: 0.3rem;
            background: linear-gradient(90deg,
                #f91f28,
                rgba(255, 79, 46, 0.35));
          }
        }
      }
    }

    .detail-tabs-scroll {
      opacity: 1;
    }
  }

  .goods-header-scroll {
    background: #fff;
    color: #777;
  }

  // 商品的内容
  .goods-info {
    .goods_photo_wrap {
      position: relative;

      .mint-swipe {
        width: 100%;
        height: 37.5rem;

        .mint-swipe-item {
          img {
            width: 100%;
            height: 100%;
          }
        }
      }

      .custom-indicator {
        position: absolute;
        bottom: 3rem;
        right: 0;
        width: 5rem;
        height: 2.5rem;
        line-height: 2.5rem;
        border-top-left-radius: 1.25rem;
        border-bottom-left-radius: 1.25rem;
        text-align: center;
        color: #fff;
        font-size: 1.4rem;
        background-color: rgba(41, 47, 54, 0.4);
        z-index: 10;

        .current {
          font-size: 1.8rem;
          color: #fff;
        }
      }
    }

    // 商品的价格
    .goods-price {
      display: flex;
      background-color: #fff;
      padding: 1.1rem 1.1rem 0.8rem;
      justify-content: space-between;
      align-items: center;
      height: 4rem;

      // 现价
      .currency-price {
        margin: 0.5rem 0;
        font-weight: 700;
        color: rgb(228, 49, 36);
        font-size: 2.4rem;

        em {
          font-size: 1.7rem;
        }
      }

      // 原价
      .rebate-price,
      .sold_out {
        margin-left: -6rem;
        font-size: 1.4rem;
        color: rgb(136, 136, 136);
      }

      .share {
        text-align: center;

        i {
          display: block;
        }
      }
    }

    // 商品的title
    .goods_title {
      padding: 1rem;
      background-color: #fff;
      border-radius: 0 0 1rem 1rem;

      .tag {
        background: linear-gradient(90deg, #f91f28, #ff4e2e);
        color: #fff;
        font-size: 1rem;
        height: 1.6rem;
        line-height: 1.6rem;
        padding: 0.2rem;
        border-radius: 0.5rem;
        margin-right: 0.5rem;
      }

      span {
        font-weight: 700;
        color: #000;
        line-height: 1.5;
        font-size: 1.5rem;
      }
    }

    // 已选内容的样式
    .goods_module_wrap {
      border-radius: 1rem;
      padding: 1.5rem 1.1rem;
      font-size: 1.4rem;
      background-color: #fff;
      margin-top: 1rem;

      .activity_content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.5rem 0;
        position: relative;
        overflow: hidden;

        // 第一个:nth-child使用1个冒号,第一个不设置&直接拼接到后面去
        &:nth-child(n + 2)::before {
          content: "";
          position: absolute;
          top: 0;
          left: 4.2rem;
          width: 100%;
          height: 0.1rem;
          background-color: #eee;
        }

        .title {
          font-weight: 700;
        }

        .activity_main {
          // width: 18.5rem;
          flex: 1;
          padding-left: 1.6rem;
        }
      }
    }
  }

  .detail_1,
  .detail_2,
  .detail_3 {
    height: 2000px;
    border: 1px solid skyblue;
    box-sizing: border-box;
  }

  .detail_2 {
    img {
      width: 100%;
    }
  }

  // 选择弹出框的样式
  .select-buy {
    .van-popup {
      width: 100%;
      height: 27.7rem;
      background-color: #fff;
      border-radius: 1.5rem 1.5rem 0 0;

      .goods-wrap {
        width: calc(100% - 2rem);
        height: 12.8rem;
        padding: 1rem;
        display: flex;

        img {
          width: 9.2rem;
          height: 9.2rem;
        }

        .goods-content {
          min-width: 23rem;

          .title {
            width: 86%;
            margin: 5%;
            height: 4rem;
            line-height: 2rem;
            font-size: 1.5rem;
            // 多行文本省略号
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }

          .currency-price {
            color: rgb(226, 44, 44);
            font-weight: 700;
            padding-left: 0.5rem;

            span {
              font-size: 1.5rem;

              em {
                font-size: 1rem;
              }
            }
          }
        }
      }

      .num-wrap {
        width: calc(100% - 2rem);
        margin: 1rem;
        height: 5rem;
        display: flex;
        justify-content: space-between;
        font-size: 1.4rem;

        h3 {
          font-size: 1.5rem;
        }

        div {
          button:first-child {
            width: 2rem;
            height: 2.8rem;
            border-radius: 0.5rem 0 0 0.5rem;
          }

          button:last-child {
            width: 2rem;
            height: 2.8rem;
            border-radius: 0 0.5rem 0.5rem 0;
          }

          .numtext {
            width: 4rem;
            height: 2.8rem;
            text-align: center;
            background-color: #eee;
            margin: 0 0.3rem;
          }
        }
      }

      .oper-wrap {
        width: calc(100% - 2rem);
        height: 4.2rem;
        display: flex;
        margin: 0 1rem;
        justify-content: space-between;

        button {
          width: 16rem;
          height: 4.2rem;
          font-weight: 700;
          color: #fff;
          border-radius: 2rem;
        }

        .addCart {
          background-color: #ffc707;
        }

        .buy {
          width: 16.7rem;
          background-color: #f91f28;
        }
      }
    }
  }

  // 底部
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: space-around;
    width: 100%;
    height: 4.2rem;
    background-color: #fff;
    color: #666;
    border-top: 0.1rem solid rgba(255, 255, 255, 0.1);
    padding: 0.5rem;

    >div {
      text-align: center;
      width: 11%;
      display: flex;
      flex-direction: column;
      font-size: 1.2rem;

      i {
        font-size: 2rem;
      }
    }

    button {
      //   flex:1 ----flex-grow: 1 flex-shink：1 flex-basis：0%;
      flex: 1;
      flex-basis: 7rem;
      border-radius: 2rem;
      font-weight: 700;
      width: 12rem;
      height: 4.2rem;
      margin-right: 1rem;
      color: #fff;
    }

    .shop {
      margin-left: 1rem;

    }

    .cart {
      position: relative;
      margin-right: 1rem;

      em {
        position: absolute;
        left: 50%;
        top: 0rem;
        height: 1.3rem;
        padding: 0 0.2rem;
        line-height: 1.3rem;
        border-radius: 0.7rem;
        border: 0.1rem solid #f91f28;
        text-align: center;
        font-size: 1.2rem;
        color: #f91f28;
        background-color: #fff;
      }
    }

    .addCart {
      background-color: #ffc707;
    }

    .buy {
      background-color: #f91f28;
    }
  }
}
</style>